/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef EL_PROTOCOL_RECORD_COMMAND_HANDLER_H
#define EL_PROTOCOL_RECORD_COMMAND_HANDLER_H

#include <string>
#include <unordered_map>
#include <nlohmann/json.hpp>
#include <mutex>
#include <chrono>
#include "command_handler_base.h"
#include "record_search.h"
#include "record_playback.h"

namespace El {
namespace Protocol {

class RecordCommandHandler : public CommandHandlerBase {
public:
    /**
     * 注册录像命令处理函数到处理器映射表
     * 
     * @param handlers 命令处理函数映射表，键为命令名称，值为处理函数
     */
    void RegisterMethodHandlers(
        std::unordered_map<std::string, std::function<nlohmann::json(const std::string &, const nlohmann::json &)>>
            &handlers);

private:
    // 搜索录像文件
    nlohmann::json HandleRecordsSearch(const std::string &id, const nlohmann::json &params);

    // 获取录像文件列表
    nlohmann::json HandleRecordsGetList(const std::string &id, const nlohmann::json &params);

    // 获取录像文件详细信息
    nlohmann::json HandleRecordsGetInfo(const std::string &id, const nlohmann::json &params);

    // 开始回放
    nlohmann::json HandlePlaybackStart(const std::string &id, const nlohmann::json &params);

    // 停止回放
    nlohmann::json HandlePlaybackStop(const std::string &id, const nlohmann::json &params);

    // 暂停回放
    nlohmann::json HandlePlaybackPause(const std::string &id, const nlohmann::json &params);

    // 恢复回放
    nlohmann::json HandlePlaybackResume(const std::string &id, const nlohmann::json &params);

    // 定位回放位置
    nlohmann::json HandlePlaybackSeek(const std::string &id, const nlohmann::json &params);

    // 设置回放速度
    nlohmann::json HandlePlaybackSetSpeed(const std::string &id, const nlohmann::json &params);

private:
    // 时间转换工具函数
    std::chrono::system_clock::time_point parseTimeString(const std::string &timeStr);
    std::string formatTimePoint(const std::chrono::system_clock::time_point &tp);
    
    // 录像文件信息转换
    nlohmann::json videoFileInfoToJson(const El::Record::VideoFileInfo &info);
    nlohmann::json imageFileInfoToJson(const El::Record::ImageFileInfo &info);

private:
    std::mutex mutex_;
    El::Record::RecordSearchPtr search_instance_;
    std::unordered_map<std::string, El::Record::PlaybackPtr> playback_instances_;
    std::unordered_map<std::string, std::string> search_sessions_; // search_id -> session_info
};

} // namespace Protocol
} // namespace El

#endif // EL_PROTOCOL_RECORD_COMMAND_HANDLER_H